<?php

namespace app\common\biz\list;

use app\common\Result;
use Exception;
use think\db\exception\DbException;
use think\Model;

class Lists
{

    protected Model $model;
    protected Search $search;

    /**
     * @param Model $model
     * @param Search $search
     */
    public function __construct(Model $model, Search $search)
    {
        $this->model = $model;
        $this->search = $search;
    }

    /**
     * @return array
     */
    public function data(): array
    {
        return ['list' => $this->lists(), 'total' => $this->total()];
    }

    /**
     * @return array
     */
    public function lists(): array
    {
        try {
            $data = $this->model
                ->field($this->search->getField())
                ->where($this->search->getParams())
                ->order($this->search->getOrder())
                ->page($this->search->getPage(), $this->search->getPageSize())
                ->select();

            return $data->isEmpty() ? [] : $data->toArray();
        } catch (DbException $e) {
            Result::dbException($e->getData());
        } catch (Exception $e) {
            Result::httpException($e->getMessage());
        }
    }

    /**
     * @return int
     */
    public function total(): int
    {
        try {
            return $this->model
                ->where($this->search->getParams())
                ->count();
        } catch (DbException $e) {
            Result::dbException($e->getData());
        } catch (Exception $e) {
            Result::httpException($e->getMessage());
        }
    }
}